package com.shfl.servermanage.bt;

import cn.hutool.json.JSONUtil;
import com.shfl.servermanage.exception.ApiException;
import com.shfl.servermanage.logic.model.info.BtUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Component
public class BtComponent {
    @Autowired
    @Qualifier("sslRestTemplate")
    private RestTemplate restTemplate;


    public String send(BtUserInfo info, Map<String, Object> map) throws Exception {
        if (map == null) {
            map = new HashMap<>();
        }
        String timestamp = (new Date().getTime() + "");
        String md5Sign = BtUtils.getMd5(info.getSecretKey());
        String temp = timestamp + md5Sign;
        String token = BtUtils.getMd5(temp);
        map.put("request_time", timestamp);
        map.put("request_token", token);
        String sendUrl = info.getAddress().concat(info.getApiUrl());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.setConnection("Keep-Alive");
        headers.set("Accept", "text/xml,text/javascript,text/html,application/json");
        //用HttpEntity封装整个请求报文
        HttpEntity<String> request = new HttpEntity<>(getRequestBodyByMap(map), headers);
        String resultString = "";
        try {
            resultString = restTemplate.postForObject(sendUrl, request, String.class);
        } catch (ResourceAccessException e) {
            if (e.getCause() instanceof UnknownHostException) {
                throw new ApiException("1201");
            }
            throw new ApiException("1200");
        }
        if (resultString.contains("Redirecting")) {
            throw new ApiException("1203");
        }
        Map resultMap = JSONUtil.parse(resultString).getByPath("", Map.class);
        if (resultMap == null) {
            throw new ApiException("1200");
        }
        if (resultMap.containsKey("status") && !(Boolean) resultMap.get("status")) {
            throw new ApiException("1200", String.valueOf(resultMap.get("msg")));
        }
        System.out.println(resultMap);
        return resultString;
    }

    public String getRequestBodyByMap(Map<String, Object> map) {
        StringBuilder result = new StringBuilder();
        if (map == null) {
            return result.toString();
        }
        Set<String> keys = map.keySet();
        for (String key : keys) {
            result.append("&");
            result.append(key);
            result.append("=");
            result.append(map.get(key));
        }
        if (result.length() > 1) {
            return result.substring(1);
        }
        return result.toString();
    }


}
